package com.nariano.webapp;

import java.util.List;
import java.util.Random;
import java.util.logging.Logger;


import org.apache.wicket.IPageMap;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.IModel;

import com.nariano.server.domain.entities.Area;
import com.nariano.server.domain.entities.City;
import com.nariano.server.domain.entities.User;
import com.nariano.server.services.mapservice.MapService;
import com.nariano.server.utils.spring.SpringFactory;

public abstract class CreateCityPage extends WebPage {

	protected static transient Logger logger;
	protected transient MapService mapService = SpringFactory.getBean("mapService",
	            MapService.class);

	protected CreateCityPage() {
		super();
		logger = getLogger();
	}

	private Logger getLogger() {
		return Logger.getLogger(getClass().getCanonicalName());
	}

	protected CreateCityPage(IModel<?> model) {
		super(model);
		logger = getLogger();
	}

	protected CreateCityPage(IPageMap pageMap) {
		super(pageMap);
		logger = getLogger();
	}

	protected CreateCityPage(PageParameters parameters) {
		super(parameters);
		logger = getLogger();
	}

	protected CreateCityPage(IPageMap pageMap, IModel<?> model) {
		super(pageMap, model);
		logger = getLogger();
	}

	protected CreateCityPage(IPageMap pageMap, PageParameters parameters) {
		super(pageMap, parameters);
		logger = Logger.getLogger(getClass().getCanonicalName());
	}

	protected void createCity(User user, City city) {
	    List<Area> areas = mapService.getAreas();
	    Area a = null;
	    Random rand = new Random();
	    for(int i=0;i<areas.size();i++) {
	        Area area = areas.get(rand.nextInt(areas.size()));
	        if (area.getCity()==null) {
	            a = area; 
	            break;
	        }
	    }
	    if (a == null) throw new IllegalStateException("Failed to find area for city");
	    // user.getUserName() + ":" + city.getName() garantuess uniquness
	    City c = new City(city.getName(), user.getId(), a.getLocation());
	    a.setCity(c);
	    mapService.updateAreas(a);
	    logger.info("Created city: " + c.toString());
	}

}